<template>
  <div class="container">
    <div class="input-area">
      <textarea v-model="text" placeholder="与圈友们分享你的个人经验" maxlength="1000"></textarea>
      <div class="bottom-options">
        <div class="file-selection">
          <el-select
              v-model="selectedCircleId"
              @change="loadMoments"
              placeholder="请选择圈子"
              style="min-width: 250px"
              :loading="circleLoading"
          >
            <el-option v-if="childCircles.length === 0" disabled value="">暂无可用圈子</el-option>
            <el-option
                v-for="circle in childCircles"
                :key="circle.id"
                :label="circle.circleName"
                :value="circle.id"
            >
              <div style="display: flex; align-items: center;">
                <img
                    :src="circle.icon"
                    style="width: 20px; height: 20px; margin-right: 10px; object-fit: cover;"
                    alt="">
                <span>{{ circle.circleName }}</span>
              </div>
            </el-option>
          </el-select>
        </div>
        <div class="action-buttons">
          <div class="icon-group">
            <el-tooltip content="添加表情" placement="top">
              <el-button
                  class="emoji-btn"
                  type="info"
                  size="small"
                  plain
                  @click.stop="toggleEmojiPicker"
              >
                <span style="font-size: 18px">😀</span>
              </el-button>
            </el-tooltip>

            <transition name="fade">
              <div v-if="showEmojiPicker" class="emoji-picker-container">
                <VEmojiPicker
                    :native="true"
                    @select="onSelectEmoji"
                    :disable-skin-tones="true"
                    theme="light"
                />
              </div>
            </transition>
          </div>

          <el-tooltip content="发布动态" placement="top">
            <el-button
                type="primary"
                size="small"
                class="publish-btn"
                @click="publish"
            >
              <el-icon><Position /></el-icon>
              发布
            </el-button>
          </el-tooltip>
        </div>
      </div>
      <p>{{ text.length }}/1000</p>

      <div class="image-upload">
        <el-upload
            :action="baseUrl + '/files/upload'"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="handleFileUpload"
            :limit="5"
            :on-exceed="handleExceed"
        >
          <i class="el-icon-plus"></i>
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </div>
    </div>

    <div class="moments-container">
      <div v-if="loading" class="loading">
        加载中...
      </div>
      <div v-else-if="moments.length === 0" class="no-moments">
        暂无动态信息
      </div>
      <div v-else class="moment-list">
        <div v-for="moment in moments" :key="moment.id" class="moment-item">
          <div class="user-info">
            <img :src="moment.userAvatar" alt="User Avatar" class="user-avatar" />
            <span class="user-name">{{ moment.userName }}</span>
          </div>
          <p><strong>{{ moment.content }}</strong></p>
          <p v-if="moment.picUrlList && moment.picUrlList.length > 0">
            <img
                v-for="(pic, index) in moment.picUrlList"
                :key="index"
                :src="pic.split(',')[0]"
                alt="Moment Image"
                class="moment-image"
                @click="openImageViewer(pic.split(',')[0])"
            />
          </p>
          <p class="moment-date">{{ formatDate(moment.createdTime) }}</p>
          <div class="moment-actions">
            <button class="action-btn" @click="share(moment)">分享</button>
            <button class="action-btn" @click="comment(moment)">评论 ({{ moment.replyCount }})</button>
          </div>
        </div>
      </div>

      <div class="pagination" v-if="totalPages > 1">
        <button @click="prevPage" :disabled="pageNum <= 1">上一页</button>
        <span>{{ pageNum }} / {{ totalPages }}</span>
        <button @click="nextPage" :disabled="pageNum >= totalPages">下一页</button>
      </div>
    </div>

    <el-image-viewer
        v-if="imageDialogVisible"
        :url-list="[clickedImageUrl]"
        @close="imageDialogVisible = false"
    />
  </div>
</template>

<script setup>
import request from "@/utils/request.js";
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElDialog } from "element-plus";
import dayjs from 'dayjs';
import VEmojiPicker from 'vue3-emoji-picker';
import 'vue3-emoji-picker/css';
import {Plus, Position} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;
const text = ref('');
const selectedCircleId = ref(null); // 初始化为null
const circles = ref([]);
const picUrlList = ref([]);
const moments = ref([]);
const loading = ref(false);
const circleLoading = ref(true); // 新增加载状态
const pageNum = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);

// 图片上传相关
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const clickedImageUrl = ref('');
const imageDialogVisible = ref(false);

// Emoji选择器
const showEmojiPicker = ref(false);
const toggleEmojiPicker = () => showEmojiPicker.value = !showEmojiPicker.value;
const onSelectEmoji = (emoji) => {
  text.value += emoji.i;
  showEmojiPicker.value = false;
};

const loadCircle = () => {
  circleLoading.value = true;
  request.get('/circle/share/circle/list').then(res => {
    if (res.code === '200') {
      circles.value = res.data;
      const childCirclesList = extractChildCircles(circles.value);
      if (childCirclesList.length > 0) {
        // 保持类型一致（数字）
        selectedCircleId.value = childCirclesList[0].id;
        loadMoments();
      }
    } else {
      ElMessage.error(res.msg);
    }
  }).finally(() => circleLoading.value = false);
};

onMounted(loadCircle);

const extractChildCircles = (circles) => {
  return circles.reduce((acc, circle) => {
    if (circle.children?.length) {
      acc.push(...extractChildCircles(circle.children));
    } else {
      acc.push(circle);
    }
    return acc;
  }, []);
};

const childCircles = computed(() => extractChildCircles(circles.value));

const publish = () => {
  if (!selectedCircleId.value) {
    ElMessage.warning('请选择一个圈子');
    return;
  }

  request.post('/circle/share/moment/save', {
    circleId: selectedCircleId.value,
    content: text.value,
    picUrlList: picUrlList.value
  }).then(res => {
    if (res.code === '200') {
      ElMessage.success('发布成功');
      text.value = '';
      picUrlList.value = [];
      loadMoments();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadMoments = () => {
  if (!selectedCircleId.value) return;

  loading.value = true;
  request.post('/circle/share/moment/getMoments',
      { circleId: selectedCircleId.value },
      { params: { pageNum: pageNum.value, pageSize: pageSize.value } }
  ).then(res => {
    if (res.code === '200') {
      moments.value = res.data?.list || [];
      totalItems.value = res.data?.total || 0;
    } else {
      ElMessage.error(res.msg);
    }
  }).finally(() => loading.value = false);
};

const nextPage = () => {
  if (pageNum.value < totalPages.value) {
    pageNum.value++;
    loadMoments();
  }
};

const prevPage = () => {
  if (pageNum.value > 1) {
    pageNum.value--;
    loadMoments();
  }
};

const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));
const formatDate = (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss');

// 图片处理函数
const beforeUpload = (file) => file.size / 1024 / 1024 < 10 || ElMessage.error('文件需小于10MB');
const handleFileUpload = (res) => res.code === '200' && picUrlList.value.push(res.data);
const handleRemove = (file) => picUrlList.value = picUrlList.value.filter(url => url !== file.response?.data);
const handleExceed = () => ElMessage.warning('最多上传5个文件');
const openImageViewer = (url) => {
  clickedImageUrl.value = url;
  imageDialogVisible.value = true;
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
const share = (moment) => {
  // 分享逻辑
  console.log('分享动态:', moment);
  // 这里可以添加具体的分享逻辑
};
const navTo = (url) => {
  location.href = url;
};
const comment = (moment) => {
  // 跳转到评论页面并携带动态ID
  navTo(`/front/plantCircleDetail?id=${moment.id}`);
};
</script>

<style scoped>
.emoji-picker-container {
  position: absolute;
  z-index: 1000;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
}
.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}
/* 图标按钮组 */
.icon-group {
  position: relative;
  display: flex;
  align-items: center;

  .emoji-btn {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    padding: 0;

    &:hover {
      background: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary-light-3);
    }
  }
}

/* 发布按钮 */
.publish-btn {
  padding: 10px 24px;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 120, 212, 0.3);
  }
}
.el-select-dropdown__item img {
  vertical-align: middle;
}
/* 调整现有按钮样式 */
.icons {
  position: relative;
  display: flex;
  gap: 8px;
}

.icons button {
  background: none;
  border: 1px solid #ddd;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.icons button:hover {
  background-color: #f0f0f0;
}

/* 调整选择器内部样式 */
:deep(.epr-emoji-category) {
  padding: 8px 0;
}

:deep(.epr-emoji:hover) {
  background-color: #f5f5f5;
  border-radius: 4px;
}

:deep(.epr-search-container input) {
  border-radius: 4px;
  border: 1px solid #ddd !important;
}
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
}

.input-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

textarea {
  width: 100%;
  height: 150px;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ccc;
  font-size: 16px;
  resize: none;
}

.bottom-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.file-selection select,
.publish-btn {
  padding: 8px 15px;
  border: 1px solid #0078d4;
  background-color: #fff;
  border-radius: 5px;
  font-size: 14px;
  color: #0078d4;
}

.publish-btn {
  background-color: #0078d4;
  color: white;
  border: none;
}

.file-selection select {
  background-color: #f1f1f1;
}

.icons button {
  background-color: #f1f1f1;
}

p {
  font-size: 14px;
  color: #888;
  margin-top: 5px;
}

.image-upload {
  margin-top: 20px;
}

.moments-container {
  margin-top: 20px;
}

.no-moments, .loading {
  text-align: center;
  font-size: 16px;
  color: #888;
}

.moment-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.moment-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.moment-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.user-name {
  font-weight: bold;
  color: #333;
}

.moment-image {
  max-width: 100px; /* 控制图片最大宽度 */
  height: auto;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer; /* 添加鼠标悬停效果 */
}

.moment-date {
  font-size: 12px;
  color: #888;
}

.moment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #0078d4;
  background-color: #fff;
  border-radius: 5px;
  font-size: 12px;
  color: #0078d4;
  margin-left: 5px;
}

.action-btn:hover {
  background-color: #eaf3ff;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 15px;
  border: 1px solid #0078d4;
  background-color: #fff;
  border-radius: 5px;
  font-size: 14px;
  color: #0078d4;
  margin: 0 5px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>



